package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.model.vo.SourceDictVO;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HongShengUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class HongShengPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
      
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", pushApiKeyParam.getApiKey());
        paramMap.put("channel", "2121");
        paramMap.put("city", city);
        paramMap.put("mobile_md5", mobileMd5);


        log.info("【弘盛】撞库开始【queryUrl】{}【bizParam】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .form(paramMap)
                .execute().body();
        log.info("【弘盛】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer errNum = resultObject.getInteger("errNum");
        String errMsg = resultObject.getString("errMsg");

        pushApiResult.setCode(String.valueOf(errNum));
        pushApiResult.setMessage(errMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(errNum), "0")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", pushApiKeyParam.getApiKey());
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("channel", "2121");


        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        paramMap.put("city", city);
        SourceDictVO sourceDictVO = memberCommonService.queryDictInfoByValue(memberSourceInfo.getLoanAmount());
        String loanAmount = sourceDictVO.getExtValue() + "0000";

        paramMap.put("money", loanAmount);
        paramMap.put("sex", HongShengUtil.getSex(memberSourceInfo.getSex()));
        paramMap.put("has_house", HongShengUtil.getSourceInfo(memberSourceInfo.getHouse()));
        paramMap.put("has_car", HongShengUtil.getSourceInfo(memberSourceInfo.getCar()));
        paramMap.put("has_baodan", HongShengUtil.getSourceInfo(memberSourceInfo.getBaoxian()));
        paramMap.put("has_gongjijin", HongShengUtil.getSourceInfo(memberSourceInfo.getGjj()));
        paramMap.put("has_weilidai", HongShengUtil.getSourceInfo(memberSourceInfo.getWeili()));

        paramMap.put("remark",this.getUserInfo(memberSourceInfo));

        log.info("【弘盛】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .form(paramMap)
                .execute().body();
        log.info("【弘盛】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer errNum = resultObject.getInteger("errNum");
        String errMsg = resultObject.getString("errMsg");

        pushApiResult.setCode(errNum + "");
        pushApiResult.setMessage(errMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(errNum), "0")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
        }else{
            pushApiResult.setPushSuccess(false);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }
    private String getUserInfo(MemberSourceInfo memberSourceInfo){
        String sex = ObjectUtil.equals(memberSourceInfo.getSex(), 1)?"男":"女";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("城市：" + memberSourceInfo.getCity()).append("；")
                .append("年龄：" + memberSourceInfo.getAge()).append("；")
                .append("性别：" + sex).append("；")
                .append("房产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHouse()).getName()).append("；")
                .append("车产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getCar()).getName()).append("；")
                .append("公积金：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGjj()).getName()).append("；")
                .append("逾期情况：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getYuqi()).getName()).append("；")
                .append("社保：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getShebao()).getName()).append("；")
                .append("保险：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaoxian()).getName()).append("；")
                .append("芝麻分：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getZhima()).getName()).append("；")
                .append("白条：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaitiao()).getName()).append("；")
                .append("花呗：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHuabei()).getName()).append("；")
        ;
        return stringBuilder.toString();
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }
}
